# -*- coding: utf-8 -*-
# Project : flacon
# File : mp3_encoder.py
# (c) Alexander Sokolov sokoloff.a@gmail.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.



import encoder
import errors
from settings import *
from flaconglobal import *
from PyQt4 import QtCore
import sys, re
import mp3_config

class Mp3Encoder(encoder.Encoder):
    id = 'MP3'
    extension = 'mp3'
    name = 'MP3'

   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def trackGainClass(cls):
        return Mp3Gain


   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def configPageClass(cls):
        return mp3_config.Mp3Config


   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def programs(cls):
        return ['lame']



   #****************************************************************
   #
   #****************************************************************
    def getEncoderArgs(self):
        args = QStringList()
        args << settings.value("Programs/lame").toString()
        args << "--silent"

        # Settings .................................................
        preset = settings.value("Mp3/Preset").toString()

        if preset == 'vbrMedium':
            args << "--preset" << "medium"

        elif preset == 'vbrStandard':
            args << "--preset" << "standard"

        elif preset == 'vbrStandardFast':
            args << "--preset" << "fast" << "standard"

        elif preset == 'vbrExtreme':
            args << "--preset" << "extreme"

        elif preset == 'vbrExtremeFast':
            args << "--preset" << "fast" << "extreme"

        elif preset == 'cbrInsane':
            args << "--preset" << "insane"

        elif preset == 'cbrKbps':
            args << "--preset" << "cbr" << settings.value("Mp3/Bitrate").toString()

        elif preset == 'abrKbps':
            args << "--preset" << settings.value("Mp3/Bitrate").toString()

        elif preset == 'vbrQuality':
            (quality, ok) = settings.value("Mp3/Quality").toInt()
            args << "-V" << QString("%1").arg(9 - quality)


        # ReplayGain ...............................................
        if settings.value("Mp3/ReplayGain") != ReplayGainTypes.Track:
            args << "--noreplaygain"

        # Tags .....................................................
        args << "--add-id3v2"
        #args << "--id3v2-only"
        if (self._track.artist()):  args << "--ta" << self._track.artist()
        if (self._track.album()):   args << "--tl" << self._track.album()
        if (self._track.genre()):   args << "--tg" << self._track.genre()
        if (self._track.year()):    args << "--ty" << str(self._track.year())
        if (self._track.title()):   args << "--tt" << self._track.title()
        if (self._track.comment()): args << "--tc" << self._track.comment()
        args << "--tn" << QString("%1/%2").arg(self._track.trackNum()).arg(self._track.trackSet().count())


        # Files ....................................................
        args << "-"
        args << self._outFile,

        return args




class Mp3Gain(encoder.Gain):
   #****************************************************************
   #
   #****************************************************************
    @classmethod
    def programs(cls):
        return ['mp3gain']



   #****************************************************************
   #
   #****************************************************************
    def getArgs(self):
        args = QStringList()
        args << settings.value("Programs/mp3gain").toString()
        args << "-a" # Album gain
        args << "-c" # ignore clipping warning when applying gain

        args << self._files

        return args


   #****************************************************************
   #
   #****************************************************************
    def parseOut(self, proc):
        buff = ''

        if len(self._trackIndexses) == 1:
            calcRe = re.compile(r"^\s*(\d{1,4})%")
            multi = False
        else:
            calcRe = re.compile(r"^\[(\d{1,4})/\d*]\s(\d{1,4})%")
            multi = True
            self._trackIndex = -1

        while True:
            if self._cancel:
                proc.terminate()
                proc.wait()
                raise errors.Abort()

            c = proc.stderr.read(1)
            if not c: break
            buff += c
            #sys.stdout.write(c)

            if (c == "\r"):
                r = calcRe.search(buff)
                if (r):

                    if multi:
                        n = self._trackIndexses[int(r.groups()[0])-1]
                        if self._trackIndex != n:
                            self.progressChanged(Statuses.CalcGain, 100)
                            self._trackIndex = n

                        percent = int(r.groups()[1])
                    else:
                        percent = int(r.groups()[0])


                    self.progressChanged(Statuses.CalcGain, percent)

                buff = ''



#****************************************************************
# Register encoder & gain classes
#****************************************************************
encoder.registerEncoder(Mp3Encoder)

